package com.samuel.basics.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.samuel.basics.annotation.CacheLock;
import com.samuel.basics.annotation.OperateLog;
import com.samuel.basics.base.BaseController;
import com.samuel.basics.constant.CommonConstant;
import com.samuel.basics.constant.OperateConstant;
import com.samuel.basics.entity.TaskCronEntity;
import com.samuel.basics.enums.ResultEnum;
import com.samuel.basics.exception.CustomException;
import com.samuel.basics.service.TaskCronService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;


/**
* <p>
* 任务管理-前端控制器
* </p>
*
* @author 黄阿能
* @since 2020-02-07
*/

@Controller
@RequestMapping("/taskCron")
public class TaskCronController extends BaseController {
    
    public static final Logger logger = LoggerFactory.getLogger(TaskCronController.class);
    
    @Resource
    private TaskCronService taskCronService;

    private final static String PREFIX = "taskCron/";

    /**
    * 跳转到任务管理首页
    */
    @GetMapping("/list")
    public String list() {
        return PREFIX + LIST;
    }

    @ResponseBody
    @GetMapping("/listJson")
    @OperateLog(operateModule = "任务管理", operateType = OperateConstant.SELECT, operateDesc = "查询任务管理列表")
    public JSONObject listJson(Page<TaskCronEntity> iPage, TaskCronEntity taskCronEntity) {
        QueryWrapper<TaskCronEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(taskCronEntity.getName())) {
            queryWrapper.lambda().like(TaskCronEntity::getName, taskCronEntity.getName());
        }
        if (StringUtils.isNotBlank(taskCronEntity.getCode())) {
            queryWrapper.lambda().like(TaskCronEntity::getCode, taskCronEntity.getCode());
        }
        iPage = taskCronService.page(iPage, queryWrapper);
        return page2LayUiTablePage(iPage);
    }

    @GetMapping("/view")
    @OperateLog(operateModule = "任务管理", operateType = OperateConstant.VIEW, operateDesc = "查看任务管理详情")
    public String view(String id, ModelMap modelMap) {
        if (StringUtils.isBlank(id)) {
            throw new CustomException(ResultEnum.GET_ERROR, "id不存在");
        }
        TaskCronEntity taskCronModel = taskCronService.getById(id);
        modelMap.put("taskCronModel", taskCronModel);
        return PREFIX + VIEW;
    }

    @GetMapping("update")
    @OperateLog(operateModule = "任务管理", operateType = OperateConstant.VIEW, operateDesc = "进入修改任务管理信息页面")
    public String toUpdate(String id, ModelMap modelMap) {
        if (StringUtils.isBlank(id)) {
            throw new CustomException(ResultEnum.UPDATE_ERROR, "请选择一条数据！");
        }

        TaskCronEntity taskCronEntity = taskCronService.getById(id);
        if (taskCronEntity == null) {
            logger.info("查询不到数据！");
            throw new CustomException(ResultEnum.UPDATE_ERROR, "请选择一条数据！");
        }
        modelMap.put("taskCronEntity", taskCronEntity);
        return PREFIX + INPUT;
    }

    @ResponseBody
    @PostMapping("/update")
    @CacheLock(prefix = "taskCron-update")
    @OperateLog(operateModule = "任务管理", operateType = OperateConstant.UPDATE, operateDesc = "修改任务管理信息")
    public JSONObject update(TaskCronEntity taskCronEntity) {
        JSONObject jsonObject = validate(taskCronEntity, CommonConstant.DATA_UPDATE_TYPE);
        Integer code = jsonObject.getInteger(CommonConstant.AjaxCode.CODE);
        if (code.equals(CommonConstant.AjaxCode.FAIL_CODE)) {
            return jsonObject;
        }

        jsonObject = new JSONObject();
        // taskCronEntity.setUpdateDate(LocalDateTime.now());
        boolean flag = taskCronService.updateById(taskCronEntity);
        if (flag) {
            jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "修改任务管理数据成功！");
            jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.SUCCESS_CODE);
        } else {
            jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "修改任务管理数据失败！");
            jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.FAIL_CODE);
        }
        return jsonObject;
    }

    @GetMapping("save")
    @OperateLog(operateModule = "任务管理", operateType = OperateConstant.VIEW, operateDesc = "跳转保存任务管理信息页面")
    public String toSave() {
        return PREFIX + INPUT;
    }

    @ResponseBody
    @PostMapping("save")
    @CacheLock(prefix = "taskCron-save")
    @OperateLog(operateModule = "任务管理", operateType = OperateConstant.SAVE, operateDesc = "保存任务管理信息")
    public JSONObject save(TaskCronEntity taskCronEntity) {
        JSONObject jsonObject = validate(taskCronEntity, CommonConstant.DATA_SAVE_TYPE);
        Integer code = jsonObject.getInteger(CommonConstant.AjaxCode.CODE);
        if (code.equals(CommonConstant.AjaxCode.FAIL_CODE)) {
            return jsonObject;
        }
        jsonObject = new JSONObject();
        try {
            taskCronEntity.setCreateDate(LocalDateTime.now());
            taskCronService.save(taskCronEntity);
            jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.SUCCESS_CODE);
            jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "保存数据成功！");
        } catch (Exception e) {
            logger.error("保存任务管理数据异常！原因：{}", e.getMessage());
            jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.FAIL_CODE);
            jsonObject.put(CommonConstant.AjaxCode.MESSAGE, e.getMessage());
        }
        return jsonObject;
    }

    /**
    * 批量删除
    *
    * @param ids id集合
    */
    @ResponseBody
    @PostMapping("delete")
    @CacheLock(prefix = "taskCron-delete")
    @OperateLog(operateModule = "任务管理", operateType = OperateConstant.DELETE, operateDesc = "删除任务管理信息，可批量删除！")
    public JSONObject delete(String ids) {
        JSONObject jsonObject = new JSONObject();
        if (StringUtils.isEmpty(ids)) {
            jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.FAIL_CODE);
            jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "请至少选择一条数据！");
            return jsonObject;
        }
        try {
            taskCronService.removeByIds(Arrays.asList(ids.split(CommonConstant.DOC_FLAG)));
            jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.SUCCESS_CODE);
            jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "删除任务管理数据成功！");
        } catch (Exception e) {
            logger.error("删除失败！原因： {}", e.getMessage());
            jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.FAIL_CODE);
            jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "删除任务管理数据失败！");
        }

        return jsonObject;
    }

    protected JSONObject validate(TaskCronEntity taskCronModel, int type) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.FAIL_CODE);
        if (taskCronModel == null) {
            jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "对象不能为空！");
            return jsonObject;
        }

        if (type == CommonConstant.DATA_UPDATE_TYPE) {
            if (StringUtils.isEmpty(taskCronModel.getId())) {
                jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "请至少选择一个对象数据！");
                return jsonObject;
            }
            // 判断任务管理是否存在
            TaskCronEntity taskCron = taskCronService.getById(taskCronModel.getId());
            if (taskCron == null) {
                jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "该数据被删除，已经不存在！");
                return jsonObject;
            }

        } else if (type == CommonConstant.DATA_SAVE_TYPE) {

        } else {
            jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.FAIL_CODE);
            jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "数据类型错误！");
            return jsonObject;
        }
        jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.SUCCESS_CODE);
        jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "数据验证成功！");
        return jsonObject;
    }

}
